package me.zhengjie.threePlc;

import lombok.RequiredArgsConstructor;
import me.zhengjie.WcsReport.WcsReportService;
import me.zhengjie.agvSend.AgvSendService;
import me.zhengjie.config.IdWorker;
import me.zhengjie.pojo.dto.*;
import me.zhengjie.pojo.entity.*;
import me.zhengjie.pojo.vo.AgvTaskSubmitVo;
import me.zhengjie.sqlservice.*;
import me.zhengjie.state.MaterialStatus;
import me.zhengjie.state.PriorityEnum;
import me.zhengjie.state.TaskStatus;
import me.zhengjie.state.TaskType;
import me.zhengjie.tcp.InboundLineBody;
import net.dreamlu.mica.core.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class LineBodyInboundTiming {
    private static final Logger lineBodyLog = LoggerFactory.getLogger("lineBody");

    private final WcsLineBodyInboundService wcsLineBodyInboundService;

    private final InboundLineBody inboundLineBody;

    private final NestingMiddleTableService nestingMiddleTableService;

    private final WcsReportService wcsReportService;

    private final WcsLineBodyAbnormalService wcsLineBodyAbnormalService;

    private final WcsLineBodyAbnormalHistoryService wcsLineBodyAbnormalHistoryService;

    private final WcsInboundMissionService wcsInboundMissionService;

    private final IdWorker idWorker;

    private final AgvSendService agvSendService;

    private final WcsInboundAbnormalMissionService wcsInboundAbnormalMissionService;

    private final IwsStoreOutsideService iwsSOutsideService;

    private final WcsConfigurationService wcsConfigurationService;

    private final WcsOutboundMissionService wcsOutboundMissionService;

    private final WcsLineEdgeWarehouseService wcsLineEdgeWarehouseService;

    @Scheduled(fixedDelay = 1000)
//    @Transactional
    public void lineBody() {
        try {
            WcsLineBodyInbound wcsLineBody = wcsLineBodyInboundService.selectOne();
            if (wcsLineBody != null) {
                Integer lineBodyInboundMove = inboundLineBody.readHoldingRegisters(1, 1);
                if (lineBodyInboundMove !=null && lineBodyInboundMove == 2) {
                    String chainMachineStorage = wcsLineBody.getChainMachineStorage();
                    String inbCtuStorage = wcsLineBody.getInbCtuStorage();
                    Integer wcsLineBodyId = wcsLineBody.getId();
                    String ngStorage = wcsLineBody.getNgStorage();
                    Integer unitId = wcsLineBody.getUnitId();
                    //高度
                    Integer tall = wcsLineBody.getTall();
                    //读码信息是否一致
                    Integer readCodeResult = wcsLineBody.getReadCodeResult();
                    //第一段料箱状态地址位
                    Integer oneWorkbinStatus = wcsLineBody.getOneWorkbinStatus();
                    //第一段读码信息地址位
                    Integer oneReadCodeInformation = wcsLineBody.getOneReadCodeInformation();
                    Integer oneWritePlc = wcsLineBody.getOneWritePlc();
                    Integer twoWritePlc = wcsLineBody.getTwoWritePlc();
                    Integer threeWritePlc = wcsLineBody.getThreeWritePlc();
                    Integer oneReadCodeResult = wcsLineBody.getOneReadCodeResult();
                    Integer twoWorkbinStatus = wcsLineBody.getTwoWorkbinStatus();
                    Integer twoReadCodeInformation = wcsLineBody.getTwoReadCodeInformation();
                    Integer twoReadCodeResult = wcsLineBody.getTwoReadCodeResult();
                    Integer threeReadCodeResult = wcsLineBody.getThreeWorkbinStatus();
                    Integer threeReadCodeInformation = wcsLineBody.getThreeReadCodeInformation();
                    Integer id = wcsLineBody.getId();
                    //入库请求搬运
                    Integer inbTransport = wcsLineBody.getInbTransport();
                    //入库反馈plc（0：无任务；1：任务中；2：已完成）
                    Integer inbFeedback = wcsLineBody.getInbFeedback();
                    Integer oneStatus = inboundLineBody.readHoldingRegisters(oneWorkbinStatus, unitId);
                    Integer twoStatus = inboundLineBody.readHoldingRegisters(twoWorkbinStatus, unitId);
                    Integer threeStatus = inboundLineBody.readHoldingRegisters(threeReadCodeResult, unitId);
                    //第一段料箱有货
                    lineBodyLog.info("第一段是否有料：{}", oneStatus);
                    if (oneStatus != null && oneStatus == 1) {
                        if (oneWritePlc == 0) {
                            //二边读码信息是否一致
                            Integer readHoldingRegisters = inboundLineBody.readHoldingRegisters(readCodeResult, unitId);
                            lineBodyLog.info("读码信息是否一致：{}", readHoldingRegisters);
                            if (readHoldingRegisters != 0) {
                                String oneContainerCode = inboundLineBody.readHoldingRegistersString(oneReadCodeInformation, unitId);
                                lineBodyLog.info("读码结果：{}", oneContainerCode);
                                if (!Objects.equals(oneContainerCode, "Null")) {
                                    String NG = null;
                                    Integer tallStatus = inboundLineBody.readHoldingRegisters(tall, unitId);
                                    lineBodyLog.info("是否超高：{}", tallStatus);
                                    if (tallStatus == 2) {
                                        NG = "超高";
                                    }
                                    lineBodyLog.info("读码信息是否一致：{}", readHoldingRegisters);
                                    if (readHoldingRegisters == 2) {
                                        if (NG == null) {
                                            NG = "读码信息不一致";
                                        } else {
                                            NG = NG + ",读码信息不一致";
                                        }
                                    }
                                    List<NestingMiddleTable> nestingMiddleTables = nestingMiddleTableService.selectContainerCode(oneContainerCode);
                                    if (nestingMiddleTables.isEmpty()) {
                                        if (NG == null) {
                                            NG = "中间表未嵌套";
                                        } else {
                                            NG = NG + ",中间表未嵌套";
                                        }
                                    }
                                    InboundIsCodeExistDto inboundIsCodeExistDto = new InboundIsCodeExistDto();
                                    inboundIsCodeExistDto.setContainerCode(oneContainerCode);
                                    inboundIsCodeExistDto.setNest(false);
                                    inboundIsCodeExistDto.setFloor("M3");
                                    boolean b = wcsReportService.inboundIsCodeExist(inboundIsCodeExistDto);
                                    if (b) {
                                        lineBodyLog.info("容器是否存在库区ng:{}", NG);
                                        if (NG == null) {
                                            NG = "容器已存在库区";
                                        } else {
                                            NG = NG + ",容器已存在库区";
                                            lineBodyLog.info("入库容器已存在库区拼接ng:{}", NG);
                                        }
                                    }
                                    //向WMS申请终点储位
                                    if (NG == null) {
                                        InboundStorageApplyDto1 inboundStorageApplyDto = new InboundStorageApplyDto1();
                                        inboundStorageApplyDto.setContainerCode(oneContainerCode);
                                        inboundStorageApplyDto.setNest(false);
                                        inboundStorageApplyDto.setFloor(TaskType.THREE_FLOOR.getMessage());
                                        ArrayList<NestingMiddleTable> materialDaos = new ArrayList<>();
                                        for (NestingMiddleTable nestingMiddleTable : nestingMiddleTables) {
                                            NestingMiddleTable nestingMiddleTable1 = new NestingMiddleTable();
                                            BeanUtils.copyProperties(nestingMiddleTable, nestingMiddleTable1);
                                            materialDaos.add(nestingMiddleTable1);
                                        }
                                        inboundStorageApplyDto.setData(materialDaos);
                                        String destination = wcsReportService.inboundStorageApply(inboundStorageApplyDto);
                                        if (destination == null) {
                                            lineBodyLog.info("入库是否找到终点储位ng:{}", NG);
                                            if (NG == null) {
                                                NG = "入库未找到终点储位";
                                            } else {
                                                NG = NG + ",入库未找到终点储位";
                                                lineBodyLog.info("入库是未找到终点储位拼接ng:{}", NG);
                                            }
                                        }

                                        WcsInboundMission wcsInboundMissions = wcsInboundMissionService.selectStorageAndContainerCode(chainMachineStorage, oneContainerCode);
                                        if (wcsInboundMissions != null) {
                                            if (NG == null) {
                                                NG = "容器编码重复";
                                            } else {
                                                NG = NG + ",容器编码重复";
                                            }
                                        }
                                        lineBodyLog.info("NG结果：{}", NG);
                                        if (NG == null) {
                                            List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectStorageAndContainerCodeS(inbCtuStorage, oneContainerCode);
                                            if (wcsInboundMissionList.isEmpty()) {
                                                // 1. 转 JSON 字符串
//                                            ObjectMapper mapper = new ObjectMapper();
//                                            String json = mapper.writerWithDefaultPrettyPrinter()
//                                                    .writeValueAsString(materialDaos);
                                                String nestingJson = JsonUtil.toJson(materialDaos);
                                                //创建入库任务
                                                String inboundCode = String.valueOf(idWorker.nextId());
                                                WcsInboundMission wcsInboundMission = new WcsInboundMission();
                                                wcsInboundMission.setInboundCode(inboundCode);
                                                wcsInboundMission.setMissionStatus(TaskStatus.Task_create.getStatus());
                                                wcsInboundMission.setContainerCode(oneContainerCode);
                                                wcsInboundMission.setSource(inbCtuStorage);
                                                wcsInboundMission.setDestination(destination);
//                                    wcsInboundMission.setDestination("AA");
                                                wcsInboundMission.setContainerType(TaskType.THREE_WORKBIN.getStatus());
                                                wcsInboundMission.setCreateTime(LocalDateTime.now());
                                                wcsInboundMission.setUpdateTime(LocalDateTime.now());
                                                wcsInboundMission.setInboundType(TaskType.inbound_ordinary.getStatus());
                                                wcsInboundMission.setFloor(TaskType.THREE_FLOOR.getMessage());
                                                wcsInboundMission.setPriority(90);
                                                wcsInboundMission.setIsNest(0);
                                                wcsInboundMission.setIsPlc(1);
                                                wcsInboundMission.setIsWms(1);
                                                wcsInboundMission.setNestingJson(nestingJson);
                                                StringBuilder sb = new StringBuilder();
                                                List<String> materialCodeList = nestingMiddleTables.stream().map(NestingMiddleTable::getMaterialCode).distinct().collect(Collectors.toList());
                                                for (String materialCode : materialCodeList) {
                                                    if (sb.length() > 0) {
                                                        sb.append(",");
                                                    }
                                                    sb.append(materialCode);
                                                }
                                                String materIalCode = sb.toString();
                                                wcsInboundMission.setMaterialCode(materIalCode);
                                                //创建入库任务
                                                lineBodyLog.info("3f创建入库任务：{}", wcsInboundMission);
                                                boolean b2 = wcsInboundMissionService.insertInbound(wcsInboundMission);
                                                if (!b2) {
                                                    lineBodyLog.error("线体创建入库任务失败，数据库异常");
                                                    throw new RuntimeException("线体创建入库任务失败，数据库异常");
                                                }
                                                //发送plc收到，标识收到
                                                lineBodyLog.info("发送plc结果：{}", 1);
                                                inboundLineBody.writeWithRetry(oneReadCodeResult, MaterialStatus.RETURN_ONE_RESULT_YES.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                                boolean b1 = wcsLineBodyInboundService.updateOneWritePlc(chainMachineStorage, 1);
                                            } else {
                                                //不为空，查询到入库任务，判断创建时间不能超过5分钟
                                                for (WcsInboundMission wcsInboundMission : wcsInboundMissionList) {
                                                    LocalDateTime createTime = wcsInboundMission.getCreateTime();
                                                    Integer missionStatus = wcsInboundMission.getMissionStatus();
                                                    LocalDateTime now = LocalDateTime.now();
                                                    long seconds = Duration.between(createTime, now).getSeconds();
                                                    if (seconds > 120 && missionStatus == 0) {
                                                        //当前料箱创建时间过长，删除任务
                                                        boolean b1 = wcsInboundMissionService.deleteInboundId(wcsInboundMission.getId());
                                                    }
                                                }

                                            }
                                        } else {
                                            //发送plc收到，标识收到
                                            lineBodyLog.info("发送plc结果：{}", 2);
                                            inboundLineBody.writeWithRetry(oneReadCodeResult, MaterialStatus.RETURN_ONE_RESULT_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                            boolean b1 = wcsLineBodyInboundService.updateOneWritePlc(chainMachineStorage, 1);
                                            List<WcsLineBodyAbnormal> wcsLineBodyAbnormals = wcsLineBodyAbnormalService.selectContainer(oneContainerCode);
                                            if (wcsLineBodyAbnormals.isEmpty()) {
                                                //记录异常表
                                                WcsLineBodyAbnormal wcsLineBodyAbnormal = new WcsLineBodyAbnormal();
                                                wcsLineBodyAbnormal.setContainerCode(oneContainerCode);
                                                wcsLineBodyAbnormal.setAbnormalInformation(NG);
                                                wcsLineBodyAbnormal.setCreateTime(LocalDateTime.now());
                                                boolean b2 = wcsLineBodyAbnormalService.inertAbnormal(wcsLineBodyAbnormal);
                                                if (!b2) {
                                                    lineBodyLog.error("创建线条异常数据失败");
                                                    throw new RuntimeException("创建线条异常数据失败");
                                                }
                                            } else {
                                                //更新异常
                                                boolean b2 = wcsLineBodyAbnormalService.updateAbnormalInformation(oneContainerCode, NG);
                                            }
                                        }
                                    } else {
                                        //发送plc收到，标识收到
                                        lineBodyLog.info("发送plc结果：{}", 2);
                                        inboundLineBody.writeWithRetry(oneReadCodeResult, MaterialStatus.RETURN_ONE_RESULT_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                        boolean b1 = wcsLineBodyInboundService.updateOneWritePlc(chainMachineStorage, 1);
                                        List<WcsLineBodyAbnormal> wcsLineBodyAbnormals = wcsLineBodyAbnormalService.selectContainer(oneContainerCode);
                                        if (wcsLineBodyAbnormals.isEmpty()) {
                                            //记录异常表
                                            WcsLineBodyAbnormal wcsLineBodyAbnormal = new WcsLineBodyAbnormal();
                                            wcsLineBodyAbnormal.setContainerCode(oneContainerCode);
                                            wcsLineBodyAbnormal.setAbnormalInformation(NG);
                                            wcsLineBodyAbnormal.setCreateTime(LocalDateTime.now());
                                            boolean b2 = wcsLineBodyAbnormalService.inertAbnormal(wcsLineBodyAbnormal);
                                            if (!b2) {
                                                lineBodyLog.error("创建线条异常数据失败");
                                                throw new RuntimeException("创建线条异常数据失败");
                                            }
                                        } else {
                                            //更新异常
                                            boolean b2 = wcsLineBodyAbnormalService.updateAbnormalInformation(oneContainerCode, NG);
                                        }
                                    }
                                } else {
                                    //记录异常表
                                    WcsLineBodyAbnormal wcsLineBodyAbnormal = new WcsLineBodyAbnormal();
                                    wcsLineBodyAbnormal.setContainerCode(oneContainerCode);
                                    wcsLineBodyAbnormal.setAbnormalInformation("PLC未读到码为NULL");
                                    wcsLineBodyAbnormal.setCreateTime(LocalDateTime.now());
                                    boolean b2 = wcsLineBodyAbnormalService.inertAbnormal(wcsLineBodyAbnormal);
                                    if (!b2) {
                                        lineBodyLog.error("创建线条异常数据失败");
                                        throw new RuntimeException("创建线条异常数据失败");
                                    }
                                    //未读到码为null
                                    //给plc发送
                                    lineBodyLog.info("发送plc结果：{}", 2);
                                    inboundLineBody.writeWithRetry(oneReadCodeResult, MaterialStatus.RETURN_ONE_RESULT_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                    boolean b1 = wcsLineBodyInboundService.updateOneWritePlc(chainMachineStorage, 1);
                                }
                            }
                        }
                    } else {
                        //无货标记set为0
                        boolean b1 = wcsLineBodyInboundService.updateOneWritePlc(chainMachineStorage, 0);
                    }
                    //第二段读码
                    if (twoStatus == 1) {
                        if (twoWritePlc == 0) {
                            //TODO 预调度CTU
//                        TaskPretaskDto taskPretaskDto = new TaskPretaskDto();
//                        taskPretaskDto.setSiteCode(TaskType.THREE_SITE_RU.getMessage());
//                        WcsConfiguration wcsConfiguration = wcsConfigurationService.selectKey(TaskType.PRE_SCHEDULING_TIME.getMessage());
//                        String configValue = wcsConfiguration.getConfigValue();
//                        taskPretaskDto.setNextTaskTime(configValue);
//                        taskPretaskDto.setRobotType(String.valueOf(TaskType.THREE_FLOOR_ROBOT_TYPE.getStatus()));
//                        AgvTaskSubmitVo agvTaskSubmitVo = agvSendService.taskPretask(taskPretaskDto);
                            String twoContainerCode = inboundLineBody.readHoldingRegistersString(twoReadCodeInformation, unitId);
                            inboundLineBody.writeWithRetry(twoReadCodeResult, MaterialStatus.RETURN_ONE_RESULT_YES.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                            //                    List<NestingMiddleTable> nestingMiddleTables = nestingMiddleTableService.selectContainerCode(twoContainerCode);
                            //                    inboundLineBody.writeWithRetry(twoReadCodeResult, MaterialStatus.RETURN_ONE_RESULT_YES.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                        }
                    } else {
                        boolean b1 = wcsLineBodyInboundService.updateTwoWritePlc(chainMachineStorage, 0);
                    }
                    //入库滚筒线前三个位置有货，或时间小于30秒
                    Integer a12IsOrNot = inboundLineBody.readHoldingRegisters(21, unitId);
                    Integer a13IsOrNot = inboundLineBody.readHoldingRegisters(22, unitId);
                    Integer a14IsOrNot = inboundLineBody.readHoldingRegisters(23, unitId);
                    LocalDateTime now1 = LocalDateTime.now();
                    LocalDateTime taskIssueTime = wcsLineBody.getTaskIssueTime();
                    long seconds = Duration.between(taskIssueTime, now1).getSeconds();
                    if (seconds < 30 && threeStatus == 1 && threeWritePlc == 0) {
                        //下发AGV任务
                        taskIssueAgv(inbTransport, unitId, threeReadCodeInformation, id, inbFeedback, chainMachineStorage, inbCtuStorage);

                    } else if ((a12IsOrNot == 1) && (a13IsOrNot == 1) && (a14IsOrNot == 1)) {
                        if (threeStatus == 1 && threeWritePlc == 0) {
                            //下发预调度
                            TaskPretaskDto taskPretaskDto = new TaskPretaskDto();
                            taskPretaskDto.setSiteCode(TaskType.THREE_SITE_RU.getMessage());
                            WcsConfiguration wcsConfiguration = wcsConfigurationService.selectKey(TaskType.PRE_SCHEDULING_TIME.getMessage());
                            String configValue = wcsConfiguration.getConfigValue();
                            taskPretaskDto.setNextTaskTime(configValue);
                            taskPretaskDto.setRobotType(String.valueOf(TaskType.THREE_FLOOR_ROBOT_TYPE.getStatus()));
                            AgvTaskSubmitVo agvTaskSubmitVo = agvSendService.taskPretask(taskPretaskDto);
                            //下发AGV任务
                            taskIssueAgv(inbTransport, unitId, threeReadCodeInformation, id, inbFeedback, chainMachineStorage, inbCtuStorage);
                        }
                    }else if (seconds >180 && threeStatus == 1 && threeWritePlc == 0){
                        lineBodyLog.info("3分钟后未有3箱，强制下发任务给AGV");
                        //下发AGV任务
                        taskIssueAgv(inbTransport, unitId, threeReadCodeInformation, id, inbFeedback, chainMachineStorage, inbCtuStorage);
                    }

                    //D3-A14读码
//                lineBodyLog.info("D3-A14读码结果：{}", threeStatus);
//                if (threeStatus == 1) {
//                    if (threeWritePlc == 0) {
//                        Integer inbTransportStatus = inboundLineBody.readHoldingRegisters(inbTransport, unitId);
//                        lineBodyLog.info("第三段有货，plc请求搬运：{}", inbTransportStatus);
//                        if (inbTransportStatus == 1) {
//                            String threeContainerCode = inboundLineBody.readHoldingRegistersString(threeReadCodeInformation, unitId);
//                            List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(threeContainerCode);
//                            lineBodyLog.info("第三段有货，查询入库任务：{}", wcsInboundMissionList);
//                            if (!wcsInboundMissionList.isEmpty()) {
//                                //发送agv，上报pcl任务执行中
//                                WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);
//                                AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
//                                agvTaskSubmitDto.setTaskType("PF-CTU-RUKU");
//                                ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
//                                TargetRoute targetRoute = new TargetRoute();
//                                TargetRoute targetRoutes = new TargetRoute();
//                                //添加起点
//                                targetRoute.setSeq(0);
//                                targetRoute.setType(TaskType.STORAGE.getMessage());
//                                targetRoute.setCode(wcsInboundMission.getSource());
//                                //添加终点
//                                targetRoutes.setSeq(1);
//                                //                            targetRoutes.setType(TaskType.STORAGE.getMessage());
//                                targetRoutes.setType(TaskType.STORAGE.getMessage());
//                                targetRoutes.setCode(wcsInboundMission.getDestination());
//                                targetRouteList.add(targetRoute);
//                                targetRouteList.add(targetRoutes);
//                                agvTaskSubmitDto.setTargetRoute(targetRouteList);
//                                agvTaskSubmitDto.setRobotTaskCode(wcsInboundMission.getInboundCode());
//                                agvTaskSubmitDto.setInitPriority(wcsInboundMission.getPriority());
//
//                                CarrierInfoDto carrierInfoDto = new CarrierInfoDto();
//                                carrierInfoDto.setCarrierCode(threeContainerCode);
//                                carrierInfoDto.setCarrierType(TaskType.TWO_Task_assignment_Container_binding.getMessage());
//                                ArrayList<CarrierInfoDto> carrierInfoDtos = new ArrayList<>();
//                                carrierInfoDtos.add(carrierInfoDto);
//                                ExtraDto extraDto = new ExtraDto();
//                                extraDto.setCarrierInfo(carrierInfoDtos);
//                                agvTaskSubmitDto.setExtra(extraDto);
//                                String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
//                                if (taskCode != null) {
//                                    //修改任务状态为1
//                                    boolean b = wcsInboundMissionService.updateMissionStatus(taskCode, TaskStatus.task_send.getStatus());
//                                    if (!b) {
//                                        lineBodyLog.error("第三段通知CTU取货，修改任务状态失败，数据异常");
//                                        throw new RuntimeException("第三段通知CTU取货，修改任务状态失败，数据异常");
//                                    }
//                                    inboundLineBody.writeWithRetry(inbFeedback, MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
//                                    boolean b1 = wcsLineBodyInboundService.updateThreeWritePlc(chainMachineStorage, 1);
//                                }
//                            } else {
//                                //未知原因导致前面未创建任务，再次创建
//                                List<NestingMiddleTable> nestingMiddleTables = nestingMiddleTableService.selectContainerCode(threeContainerCode);
//                                InboundStorageApplyDto1 inboundStorageApplyDto = new InboundStorageApplyDto1();
//                                inboundStorageApplyDto.setContainerCode(threeContainerCode);
//                                inboundStorageApplyDto.setNest(false);
//                                inboundStorageApplyDto.setFloor(TaskType.THREE_FLOOR.getMessage());
//                                ArrayList<NestingMiddleTable> materialDaos = new ArrayList<>();
//                                for (NestingMiddleTable nestingMiddleTable : nestingMiddleTables) {
//                                    NestingMiddleTable nestingMiddleTable1 = new NestingMiddleTable();
//                                    BeanUtils.copyProperties(nestingMiddleTable, nestingMiddleTable1);
//                                    materialDaos.add(nestingMiddleTable1);
//                                }
//                                inboundStorageApplyDto.setData(materialDaos);
//                                String destination = wcsReportService.inboundStorageApply(inboundStorageApplyDto);
//
//                                String inboundCode = String.valueOf(idWorker.nextId());
//                                WcsInboundMission wcsInboundMission = new WcsInboundMission();
//                                wcsInboundMission.setInboundCode(inboundCode);
//                                wcsInboundMission.setMissionStatus(TaskStatus.Task_create.getStatus());
//                                wcsInboundMission.setContainerCode(threeContainerCode);
//                                wcsInboundMission.setSource(inbCtuStorage);
//                                wcsInboundMission.setDestination(destination);
////                                    wcsInboundMission.setDestination("AA");
//                                wcsInboundMission.setContainerType(TaskType.THREE_WORKBIN.getStatus());
//                                wcsInboundMission.setCreateTime(LocalDateTime.now());
//                                wcsInboundMission.setUpdateTime(LocalDateTime.now());
//                                wcsInboundMission.setInboundType(TaskType.inbound_ordinary.getStatus());
//                                wcsInboundMission.setFloor(TaskType.THREE_FLOOR.getMessage());
//                                wcsInboundMission.setPriority(90);
//                                wcsInboundMission.setIsNest(0);
//                                wcsInboundMission.setIsPlc(1);
//                                wcsInboundMission.setIsWms(1);
//                                StringBuilder sb = new StringBuilder();
//                                List<String> materialCodeList = nestingMiddleTables.stream().map(NestingMiddleTable::getMaterialCode).distinct().collect(Collectors.toList());
//                                for (String materialCode : materialCodeList) {
//                                    if (sb.length() > 0) {
//                                        sb.append(",");
//                                    }
//                                    sb.append(materialCode);
//                                }
//                                String materIalCode = sb.toString();
//                                wcsInboundMission.setMaterialCode(materIalCode);
//                                //创建入库任务
//                                lineBodyLog.info("再次创建3f创建入库任务：{}", wcsInboundMission);
//                                boolean b2 = wcsInboundMissionService.insertInbound(wcsInboundMission);
//                                if (!b2) {
//                                    lineBodyLog.error("线体创建入库任务失败，数据库异常");
//                                    throw new RuntimeException("线体创建入库任务失败，数据库异常");
//                                }
//                            }
//                        }
//                    }
//                }
                    if (threeStatus == 0 && threeWritePlc == 1) {
                        boolean b1 = wcsLineBodyInboundService.updateThreeWritePlc(chainMachineStorage, 0);
                    }

                    //ng栈板搬运
                    Integer ngRequest = wcsLineBody.getNgRequest();
                    Integer ngWritePlc = wcsLineBody.getNgWritePlc();
                    Integer ngTransport = wcsLineBody.getNgTransport();
                    Integer ngSize = inboundLineBody.readHoldingRegisters(ngRequest, unitId);
                    if (ngSize == 1) {
                        if (ngWritePlc == 0) {
                            //todo 查询终点异常区有储位 终点储位上锁
                            //查询NG栈板储位终点
//                        List<WcsLineEdgeWarehouse> wcsLineEdgeWarehouses = wcsLineEdgeWarehouseService.selectRegionAndStatus(TaskType.STORAGE_TYPE_THREE_FLOOR_NEW_ABNORMAL.getMessage(), 0);
                            List<WcsLineEdgeWarehouse> wcsLineEdgeWarehouses = wcsLineEdgeWarehouseService.selectGoodTypeAndStatus(TaskType.STORAGE_TYPE_THREE_FLOOR_NEW_ABNORMAL.getMessage(), 0);
//                        List<WcsLineEdgeWarehouse> wcsLineEdgeWarehouses = wcsLineEdgeWarehouseService.selectRegionAndStatus("F3出库", 0);
                            if (!wcsLineEdgeWarehouses.isEmpty()) {
                                WcsLineEdgeWarehouse wcsLineEdgeWarehouse = wcsLineEdgeWarehouses.get(0);
                                String storageCode = wcsLineEdgeWarehouse.getStorageCode();
                                //将终点储位标记agv搬运
                                wcsLineEdgeWarehouseService.updateStatusIsAgv(storageCode, null, TaskStatus.LINE_EDGE_WAREHOUSE_RESERVED.getStatus(), 1);
                                //                        iwsSOutsideService.updateStatus(id,null,1);
                                String inboundAbnormal = String.valueOf(idWorker.nextId());
                                //储位绑定栈板
//                            CarrierUnbindDto carrierUnbindDto = new CarrierUnbindDto();
//                            carrierUnbindDto.setSlotCategory(TaskType.SITE.getMessage());
//                            carrierUnbindDto.setSlotCode(ngStorage);
//                            carrierUnbindDto.setCarrierCategory("SITE");
//                            carrierUnbindDto.setCarrierType("1");
//                            carrierUnbindDto.setInvoke(TaskType.BIND.getMessage());
//                            agvSendService.carrierUnbind(carrierUnbindDto);
                                AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
                                agvTaskSubmitDto.setTaskType("QC-A1");
                                ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
                                TargetRoute targetRoute = new TargetRoute();
                                TargetRoute targetRoutes = new TargetRoute();
                                //添加起点
                                targetRoute.setSeq(0);
                                targetRoute.setType(TaskType.SITE.getMessage());
                                targetRoute.setCode(ngStorage);
                                //添加终点
                                targetRoutes.setSeq(1);
                                targetRoutes.setType(TaskType.SITE.getMessage());
                                targetRoutes.setCode(storageCode);
                                targetRouteList.add(targetRoute);
                                targetRouteList.add(targetRoutes);
                                agvTaskSubmitDto.setTargetRoute(targetRouteList);
                                agvTaskSubmitDto.setRobotTaskCode(inboundAbnormal);
                                agvTaskSubmitDto.setInitPriority(PriorityEnum.FOUR.getWeight());
                                String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
                                if (taskCode != null) {
                                    WcsInboundAbnormalMission wcsInboundAbnormalMission = new WcsInboundAbnormalMission();
                                    wcsInboundAbnormalMission.setAbnormalCode(inboundAbnormal);
                                    wcsInboundAbnormalMission.setMissionStatus(TaskStatus.Task_create.getStatus());
                                    wcsInboundAbnormalMission.setContainerCode("3楼线体异常栈板");
                                    wcsInboundAbnormalMission.setSource(ngStorage);
                                    wcsInboundAbnormalMission.setDestination(storageCode);
                                    wcsInboundAbnormalMission.setContainerType(TaskType.THREE_WORKBIN.getStatus());
                                    wcsInboundAbnormalMission.setCreateTime(LocalDateTime.now());
                                    wcsInboundAbnormalMission.setUpdateTime(LocalDateTime.now());
                                    wcsInboundAbnormalMission.setAbnormal("当前栈板都是异常料箱");
                                    boolean b = wcsInboundAbnormalMissionService.insertAbnormal(wcsInboundAbnormalMission);
                                    if (!b) {
                                        lineBodyLog.error("创建入库任务失败");
                                        throw new RuntimeException("创建入库任务失败");
                                    }
                                    //通知plc任务执行中
                                    inboundLineBody.writeWithRetry(ngTransport, MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                    boolean b1 = wcsLineBodyInboundService.updateNgWritePlc(chainMachineStorage, 1);
                                }
                            }
                        }
                    } else {
                        boolean b1 = wcsLineBodyInboundService.updateNgWritePlc(chainMachineStorage, 0);
                    }
                    //需要补空栈板
                    Integer transportEmptyPallet = wcsLineBody.getTransportEmptyPallet();
                    String hoistStorage = wcsLineBody.getHoistStorage();
                    Integer transportReply = wcsLineBody.getHoiStTransportReply();
                    Integer emptyPalletStatus = inboundLineBody.readHoldingRegisters(transportEmptyPallet, unitId);
                    lineBodyLog.info("是否需要补空栈板：{}", emptyPalletStatus);
                    //需要补空栈板
                    Integer hoistRepairPlc = wcsLineBody.getHoistRepairPlc();
                    if (emptyPalletStatus == 2) {
                        if (hoistRepairPlc == 0) {
                            //查询3楼空栈板储位是否有货
                            //                    List<IwsSOutside> iwsSOutsideList = iwsSOutsideService.selectStoreTypeStatus(TaskType.STORAGE_TYPE_THREE_FLOOR_EMPTY_PALLET.getMessage(), 3);
//                        List<WcsLineEdgeWarehouse> wcsLineEdgeWarehouseList = wcsLineEdgeWarehouseService.selectRegionInStatus(TaskType.STORAGE_TYPE_THREE_FLOOR_EMPTY_PALLET.getMessage(), TaskStatus.LINE_EDGE_WAREHOUSE_OCCUPIED.getStatus(), TaskStatus.LINE_EDGE_WAREHOUSE_MANUAL_LOAD.getStatus());
                            List<WcsLineEdgeWarehouse> wcsLineEdgeWarehouseList = wcsLineEdgeWarehouseService.selectGoodTypeInStatus(TaskType.STORAGE_TYPE_THREE_FLOOR_EMPTY_PALLET.getMessage(), TaskStatus.LINE_EDGE_WAREHOUSE_OCCUPIED.getStatus(), TaskStatus.LINE_EDGE_WAREHOUSE_MANUAL_LOAD.getStatus());
                            if (!wcsLineEdgeWarehouseList.isEmpty()) {
                                WcsLineEdgeWarehouse wcsLineEdgeWarehouse = wcsLineEdgeWarehouseList.get(0);
                                //发送agv搬运补空栈板
                                String storageCode = wcsLineEdgeWarehouse.getStorageCode();
                                //储位绑定栈板
                                String inboundCode = String.valueOf(idWorker.nextId());
                                AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
                                agvTaskSubmitDto.setTaskType("QC-A1");
                                ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
                                TargetRoute targetRoute = new TargetRoute();
                                TargetRoute targetRoutes = new TargetRoute();
                                //添加起点
                                targetRoute.setSeq(0);
                                targetRoute.setType(TaskType.SITE.getMessage());
                                targetRoute.setCode(storageCode);
                                //添加终点
                                targetRoutes.setSeq(1);
                                targetRoutes.setType(TaskType.SITE.getMessage());
                                targetRoutes.setCode(hoistStorage);
                                targetRouteList.add(targetRoute);
                                targetRouteList.add(targetRoutes);
                                agvTaskSubmitDto.setTargetRoute(targetRouteList);
                                agvTaskSubmitDto.setRobotTaskCode(inboundCode);
                                agvTaskSubmitDto.setInitPriority(PriorityEnum.FOUR.getWeight());
                                String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
                                if (taskCode != null) {
                                    //创建入库任务
                                    WcsInboundMission wcsInboundMission = new WcsInboundMission();
                                    //生成入库任务
                                    wcsInboundMission.setInboundCode(inboundCode);
                                    wcsInboundMission.setMissionStatus(TaskStatus.task_send.getStatus());
                                    wcsInboundMission.setContainerCode("空托盘");
                                    wcsInboundMission.setSource(storageCode);
                                    wcsInboundMission.setDestination(hoistStorage);
                                    wcsInboundMission.setContainerType(TaskType.EMPTY_PALLET_STORAGE.getStatus());
                                    wcsInboundMission.setCreateTime(LocalDateTime.now());
                                    wcsInboundMission.setUpdateTime(LocalDateTime.now());
                                    wcsInboundMission.setInboundType(TaskType.inbound_ordinary.getStatus());
                                    wcsInboundMission.setIsNest(0);
                                    wcsInboundMission.setFloor("3");
                                    wcsInboundMission.setPriority(90);
                                    wcsInboundMission.setIsPlc(1);
                                    wcsInboundMission.setIsWms(0);
                                    boolean b = wcsInboundMissionService.insertInbound(wcsInboundMission);
                                    if (!b) {
                                        lineBodyLog.error("空栈板入库提升机创建任务失败，数据库异常");
                                        throw new RuntimeException("空栈板入库提升机创建任务失败，数据库异常");
                                    }
                                    //库外储位锁定
                                    boolean b2 = wcsLineEdgeWarehouseService.updateStatusIsAgv(storageCode, null, TaskStatus.LINE_EDGE_WAREHOUSE_RESERVED.getStatus(), 1);
                                    //                            iwsSOutsideService.updateStatus(storageCode,2);
                                    lineBodyLog.info("发送plc请求地址位：{}，参数：{}", transportReply, MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus());
                                    //发送plc任务执行中
                                    inboundLineBody.writeWithRetry(transportReply, MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                    //修改补空栈板状态为1
                                    boolean b1 = wcsLineBodyInboundService.updateHoistRepairPlc(wcsLineBodyId, 1);
                                }
                            }
                        }
                    } else if (emptyPalletStatus == 1) {
                        if (hoistRepairPlc == 0) {
                            //查询3楼空栈板储位是否有储位
                            //                    List<IwsSOutside> iwsSOutsideList = iwsSOutsideService.selectStoreTypeStatus(TaskType.STORAGE_TYPE_THREE_FLOOR_EMPTY_PALLET.getMessage(), 0);
//                        List<WcsLineEdgeWarehouse> wcsLineEdgeWarehouses = wcsLineEdgeWarehouseService.selectRegionAndStatus(TaskType.STORAGE_TYPE_THREE_FLOOR_EMPTY_PALLET.getMessage(), 0);
                            List<WcsLineEdgeWarehouse> wcsLineEdgeWarehouses = wcsLineEdgeWarehouseService.selectGoodTypeAndStatus(TaskType.STORAGE_TYPE_THREE_FLOOR_EMPTY_PALLET.getMessage(), 0);
                            if (!wcsLineEdgeWarehouses.isEmpty()) {
                                WcsLineEdgeWarehouse wcsLineEdgeWarehouse = wcsLineEdgeWarehouses.get(0);
                                //发送agv搬运空栈板
                                String storageCode = wcsLineEdgeWarehouse.getStorageCode();
                                //储位绑定栈板
                                String outboundCode = String.valueOf(idWorker.nextId());
                                CarrierUnbindDto carrierUnbindDto = new CarrierUnbindDto();
                                carrierUnbindDto.setSlotCategory(TaskType.SITE.getMessage());
                                carrierUnbindDto.setSlotCode(hoistStorage);
                                carrierUnbindDto.setCarrierCategory("PALLET");
                                carrierUnbindDto.setCarrierType("1");
                                carrierUnbindDto.setInvoke(TaskType.BIND.getMessage());
                                agvSendService.carrierUnbind(carrierUnbindDto);

                                AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
                                //                        //todo 任务类型，根据现场情况来定
//                            agvTaskSubmitDto.setTaskType(TaskType.PF_FMR_COMMON.getMessage());
                                agvTaskSubmitDto.setTaskType("QC-A1");
                                ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
                                TargetRoute targetRoute = new TargetRoute();
                                TargetRoute targetRoutes = new TargetRoute();
                                //添加起点
                                targetRoute.setSeq(0);
                                targetRoute.setType(TaskType.SITE.getMessage());
                                targetRoute.setCode(hoistStorage);
                                //添加终点
                                targetRoutes.setSeq(1);
                                targetRoutes.setType(TaskType.SITE.getMessage());
                                targetRoutes.setCode(storageCode);
                                targetRouteList.add(targetRoute);
                                targetRouteList.add(targetRoutes);
                                agvTaskSubmitDto.setTargetRoute(targetRouteList);
                                agvTaskSubmitDto.setRobotTaskCode(outboundCode);
                                agvTaskSubmitDto.setInitPriority(PriorityEnum.FOUR.getWeight());
                                String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
                                if (taskCode != null) {
                                    //创建出库任务
                                    WcsOutboundMission wcsOutboundMission = new WcsOutboundMission();
                                    wcsOutboundMission.setOutboundCode(outboundCode);
                                    wcsOutboundMission.setMissionStatus(TaskStatus.task_send.getStatus());
                                    wcsOutboundMission.setContainerCode("空托盘" + outboundCode);
                                    wcsOutboundMission.setSource(hoistStorage);
                                    wcsOutboundMission.setDestination(storageCode);
                                    wcsOutboundMission.setCreateTime(LocalDateTime.now());
                                    wcsOutboundMission.setUpdateTime(LocalDateTime.now());
                                    wcsOutboundMission.setContainerType(TaskType.EMPTY_OUTBOUND_STORAGE.getStatus());
                                    wcsOutboundMission.setPriority(99);
//                                                            wcsOutboundMission.setTaskType(taskType);
                                    wcsOutboundMission.setIsNest(0);
                                    wcsOutboundMission.setIsWms(0);
                                    wcsOutboundMission.setFloor("3");
                                    //                            wcsOutboundMission.setWmsTaskId(wmsTaskId);
                                    boolean b = wcsOutboundMissionService.insertOutbound(wcsOutboundMission);
                                    if (!b) {
                                        lineBodyLog.error("空栈板入库提升机创建任务失败，数据库异常");
                                        throw new RuntimeException("空栈板入库提升机创建任务失败，数据库异常");
                                    }
                                    //库外储位锁定
                                    //                            iwsSOutsideService.updateStatus(id,1);
                                    boolean b2 = wcsLineEdgeWarehouseService.updateStatusIsAgv(storageCode, null, TaskStatus.LINE_EDGE_WAREHOUSE_RESERVED.getStatus(), 1);
                                    //发送plc任务执行中
                                    lineBodyLog.info("搬运空栈板地址位:{},发送参数：{}", transportReply, MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus());
                                    inboundLineBody.writeWithRetry(transportReply, MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                    //修改补空栈板状态为1
                                    boolean b1 = wcsLineBodyInboundService.updateHoistRepairPlc(wcsLineBodyId, 1);
                                }
                            }
                        }
                    } else {
                        //不需要补空栈板，写为0
                        boolean b1 = wcsLineBodyInboundService.updateHoistRepairPlc(wcsLineBodyId, 0);
                    }

//
//                lineBodyLog.info("搬运空栈板请求参数：{}",emptyPalletStatusStatus);
//                //搬运空栈板
//                if (emptyPalletStatusStatus == 1) {
//                    Integer hoistTakePlc = wcsLineBody.getHoistTakePlc();
//                    if (hoistTakePlc == 0) {
//                        //查询3楼空栈板储位是否有储位
//    //                    List<IwsSOutside> iwsSOutsideList = iwsSOutsideService.selectStoreTypeStatus(TaskType.STORAGE_TYPE_THREE_FLOOR_EMPTY_PALLET.getMessage(), 0);
//                        List<WcsLineEdgeWarehouse> wcsLineEdgeWarehouses = wcsLineEdgeWarehouseService.selectRegionAndStatus(TaskType.STORAGE_TYPE_THREE_FLOOR_EMPTY_PALLET.getMessage(), 0);
//                        if (!wcsLineEdgeWarehouses.isEmpty()){
//                            WcsLineEdgeWarehouse wcsLineEdgeWarehouse = wcsLineEdgeWarehouses.get(0);
//                            //发送agv搬运补空栈板
//                            String storageCode = wcsLineEdgeWarehouse.getStorageCode();
//                            //储位绑定栈板
//                            String outboundCode = String.valueOf(idWorker.nextId());
//                            CarrierUnbindDto carrierUnbindDto = new CarrierUnbindDto();
//                            carrierUnbindDto.setSlotCategory(TaskType.SITE.getMessage());
//                            carrierUnbindDto.setSlotCode(hoistStorage);
//                            carrierUnbindDto.setCarrierCategory("PALLET");
//                            carrierUnbindDto.setCarrierType("1");
//                            carrierUnbindDto.setInvoke(TaskType.BIND.getMessage());
//                            agvSendService.carrierUnbind(carrierUnbindDto);
//
//                            AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
//    //                        //todo 任务类型，根据现场情况来定
////                            agvTaskSubmitDto.setTaskType(TaskType.PF_FMR_COMMON.getMessage());
//                            agvTaskSubmitDto.setTaskType("QC-A1");
//                            ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
//                            TargetRoute targetRoute = new TargetRoute();
//                            TargetRoute targetRoutes = new TargetRoute();
//                            //添加起点
//                            targetRoute.setSeq(0);
//                            targetRoute.setType(TaskType.SITE.getMessage());
//                            targetRoute.setCode(hoistStorage);
//                            //添加终点
//                            targetRoutes.setSeq(1);
//                            targetRoutes.setType(TaskType.SITE.getMessage());
//                            targetRoutes.setCode(storageCode);
//                            targetRouteList.add(targetRoute);
//                            targetRouteList.add(targetRoutes);
//                            agvTaskSubmitDto.setTargetRoute(targetRouteList);
//                            agvTaskSubmitDto.setRobotTaskCode(outboundCode);
//                            agvTaskSubmitDto.setInitPriority(PriorityEnum.FOUR.getWeight());
//                            String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
//                            if (taskCode !=null){
//                                //创建出库任务
//                                WcsOutboundMission wcsOutboundMission = new WcsOutboundMission();
//                                wcsOutboundMission.setOutboundCode(outboundCode);
//                                wcsOutboundMission.setMissionStatus(TaskStatus.task_send.getStatus());
//                                wcsOutboundMission.setContainerCode("空托盘" +outboundCode);
//                                wcsOutboundMission.setSource(hoistStorage);
//                                wcsOutboundMission.setDestination(storageCode);
//                                wcsOutboundMission.setCreateTime(LocalDateTime.now());
//                                wcsOutboundMission.setUpdateTime(LocalDateTime.now());
//                                wcsOutboundMission.setContainerType(TaskType.EMPTY_OUTBOUND_STORAGE.getStatus());
//                                wcsOutboundMission.setPriority(99);
//    //                            wcsOutboundMission.setTaskType(taskType);
//                                wcsOutboundMission.setIsNest(0);
//                                wcsOutboundMission.setIsWms(0);
//                                wcsOutboundMission.setFloor("3");
//    //                            wcsOutboundMission.setWmsTaskId(wmsTaskId);
//                                boolean b = wcsOutboundMissionService.insertOutbound(wcsOutboundMission);
//                                if (!b){
//                                    lineBodyLog.error("空栈板入库提升机创建任务失败，数据库异常");
//                                    throw new RuntimeException("空栈板入库提升机创建任务失败，数据库异常");
//                                }
//                                //库外储位锁定
//    //                            iwsSOutsideService.updateStatus(id,1);
//                                boolean b2 = wcsLineEdgeWarehouseService.updateStatusIsAgv(storageCode, null, TaskStatus.LINE_EDGE_WAREHOUSE_RESERVED.getStatus(), 1);
//                                //发送plc任务执行中
//                                lineBodyLog.info("搬运空栈板地址位:{},发送参数：{}",transportReply,MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus());
//                                inboundLineBody.writeWithRetry(transportReply,MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus(),unitId,MaterialStatus.RETRY_COUNT.getStatus());
//                                //修改补空栈板状态为1
//                                boolean b1 = wcsLineBodyInboundService.updateHoistakePlc(wcsLineBodyId,1);
//                            }
//                        }
//                    }
//                } else {
//                    //不需要取空栈板，写为0
//                    boolean b1 = wcsLineBodyInboundService.updateHoistakePlc(wcsLineBodyId, 0);
//                }

                    //查询写入PLC，一分钟未变化，修改为0
                    LocalDateTime oneTime = wcsLineBody.getOneTime();
                    LocalDateTime twoTime = wcsLineBody.getTwoTime();
                    LocalDateTime threeTime = wcsLineBody.getThreeTime();
                    LocalDateTime now = LocalDateTime.now();
                    if (oneTime != null) {
                        long oneWrite = Duration.between(oneTime, now).getSeconds();
                        if (oneWrite > 60 && oneWritePlc == 1) {
                            //无货标记set为0
                            boolean b1 = wcsLineBodyInboundService.updateOneWritePlc(chainMachineStorage, 0);
                        }
                    }
                    if (twoTime != null) {
                        long twoWrite = Duration.between(twoTime, now).getSeconds();
                        if (twoWrite > 60 && twoWritePlc == 1) {
                            boolean b1 = wcsLineBodyInboundService.updateTwoWritePlc(chainMachineStorage, 0);
                        }
                    }
                    if (threeTime != null) {
                        long threeWrite = Duration.between(threeTime, now).getSeconds();
                        if (threeWrite > 60 && threeWritePlc == 1) {
                            boolean b1 = wcsLineBodyInboundService.updateThreeWritePlc(chainMachineStorage, 0);
                        }
                    }
                }
            }
            //根据创建时间删除3楼问题
            List<WcsLineBodyAbnormal> wcsLineBodyAbnormalList = wcsLineBodyAbnormalService.selectAll();
            if (!wcsLineBodyAbnormalList.isEmpty()) {
                for (WcsLineBodyAbnormal wcsLineBodyAbnormal : wcsLineBodyAbnormalList) {
                    Integer id = wcsLineBodyAbnormal.getId();
                    LocalDateTime createTime = wcsLineBodyAbnormal.getCreateTime();
                    LocalDateTime now = LocalDateTime.now();
                    long hours = Duration.between(createTime, now).toHours();
                    WcsConfiguration wcsConfiguration = wcsConfigurationService.selectKey(TaskType.THREE_FLOOR_MATERIAL_BOX_ABNORMAL_STORAGE_TIME.getMessage());
                    if (wcsConfiguration != null) {
                        String value = wcsConfiguration.getConfigValue();
                        Integer i = Integer.valueOf(value);
                        if (hours > i) {
                            //移到历史表
                            WcsLineBodyAbnormalHistory wcsLineBodyAbnormalHistory = new WcsLineBodyAbnormalHistory();
                            BeanUtils.copyProperties(wcsLineBodyAbnormal, wcsLineBodyAbnormalHistory);
                            wcsLineBodyAbnormalHistory.setId(null);
                            boolean b = wcsLineBodyAbnormalHistoryService.insert(wcsLineBodyAbnormalHistory);
                            if (!b) {
                                lineBodyLog.error("创建线体异常历史任务失败，数据异常");
                                throw new RuntimeException("创建线体异常历史任务失败，数据异常");
                            }
                            //删除任务
                            boolean b1 = wcsLineBodyAbnormalService.delectId(id);
                            if (!b1) {
                                lineBodyLog.error("删除线体数据失败，数据异常");
                                throw new RuntimeException("删除线体数据失败，数据异常");
                            }
                        }
                    }
                }
            }
        } catch (RuntimeException e) {
            lineBodyLog.error("catch报错信息：", e);
            throw new RuntimeException(e);
        }
    }

    private void taskIssueAgv(Integer inbTransport, Integer unitId, Integer threeReadCodeInformation, Integer id, Integer inbFeedback, String chainMachineStorage, String inbCtuStorage) {
        Integer inbTransportStatus = inboundLineBody.readHoldingRegisters(inbTransport, unitId);
        lineBodyLog.info("第三段有货，plc请求搬运：{}", inbTransportStatus);
        if (inbTransportStatus == 1) {
            String threeContainerCode = inboundLineBody.readHoldingRegistersString(threeReadCodeInformation, unitId);
            List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(threeContainerCode);
            lineBodyLog.info("第三段有货，查询入库任务：{}", wcsInboundMissionList);
            if (!wcsInboundMissionList.isEmpty()) {
                //发送agv，上报pcl任务执行中
                WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);
                AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
                agvTaskSubmitDto.setTaskType("PF-CTU-RUKU");
                ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
                TargetRoute targetRoute = new TargetRoute();
                TargetRoute targetRoutes = new TargetRoute();
                //添加起点
                targetRoute.setSeq(0);
                targetRoute.setType(TaskType.STORAGE.getMessage());
                targetRoute.setCode(wcsInboundMission.getSource());
                //添加终点
                targetRoutes.setSeq(1);
                //                            targetRoutes.setType(TaskType.STORAGE.getMessage());
                targetRoutes.setType(TaskType.STORAGE.getMessage());
                targetRoutes.setCode(wcsInboundMission.getDestination());
                targetRouteList.add(targetRoute);
                targetRouteList.add(targetRoutes);
                agvTaskSubmitDto.setTargetRoute(targetRouteList);
                agvTaskSubmitDto.setRobotTaskCode(wcsInboundMission.getInboundCode());
                agvTaskSubmitDto.setInitPriority(wcsInboundMission.getPriority());

                CarrierInfoDto carrierInfoDto = new CarrierInfoDto();
                carrierInfoDto.setCarrierCode(threeContainerCode);
                carrierInfoDto.setCarrierType(TaskType.TWO_Task_assignment_Container_binding.getMessage());
                ArrayList<CarrierInfoDto> carrierInfoDtos = new ArrayList<>();
                carrierInfoDtos.add(carrierInfoDto);
                ExtraDto extraDto = new ExtraDto();
                extraDto.setCarrierInfo(carrierInfoDtos);
                agvTaskSubmitDto.setExtra(extraDto);
                String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
                if (taskCode != null) {
                    //更新任务下发时间
                    boolean b2 = wcsLineBodyInboundService.updateTaskIssueTime(id);
                    //修改任务状态为1
                    boolean b = wcsInboundMissionService.updateMissionStatus(taskCode, TaskStatus.task_send.getStatus());
                    if (!b) {
                        lineBodyLog.error("第三段通知CTU取货，修改任务状态失败，数据异常");
                        throw new RuntimeException("第三段通知CTU取货，修改任务状态失败，数据异常");
                    }
                    inboundLineBody.writeWithRetry(inbFeedback, MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                    boolean b1 = wcsLineBodyInboundService.updateThreeWritePlc(chainMachineStorage, 1);
                }
            } else {
                //未知原因导致前面未创建任务，再次创建
                List<NestingMiddleTable> nestingMiddleTables = nestingMiddleTableService.selectContainerCode(threeContainerCode);
                InboundStorageApplyDto1 inboundStorageApplyDto = new InboundStorageApplyDto1();
                inboundStorageApplyDto.setContainerCode(threeContainerCode);
                inboundStorageApplyDto.setNest(false);
                inboundStorageApplyDto.setFloor(TaskType.THREE_FLOOR.getMessage());
                ArrayList<NestingMiddleTable> materialDaos = new ArrayList<>();
                for (NestingMiddleTable nestingMiddleTable : nestingMiddleTables) {
                    NestingMiddleTable nestingMiddleTable1 = new NestingMiddleTable();
                    BeanUtils.copyProperties(nestingMiddleTable, nestingMiddleTable1);
                    materialDaos.add(nestingMiddleTable1);
                }
                inboundStorageApplyDto.setData(materialDaos);
                String destination = wcsReportService.inboundStorageApply(inboundStorageApplyDto);

                String inboundCode = String.valueOf(idWorker.nextId());
                WcsInboundMission wcsInboundMission = new WcsInboundMission();
                wcsInboundMission.setInboundCode(inboundCode);
                wcsInboundMission.setMissionStatus(TaskStatus.Task_create.getStatus());
                wcsInboundMission.setContainerCode(threeContainerCode);
                wcsInboundMission.setSource(inbCtuStorage);
                wcsInboundMission.setDestination(destination);
//                                    wcsInboundMission.setDestination("AA");
                wcsInboundMission.setContainerType(TaskType.THREE_WORKBIN.getStatus());
                wcsInboundMission.setCreateTime(LocalDateTime.now());
                wcsInboundMission.setUpdateTime(LocalDateTime.now());
                wcsInboundMission.setInboundType(TaskType.inbound_ordinary.getStatus());
                wcsInboundMission.setFloor(TaskType.THREE_FLOOR.getMessage());
                wcsInboundMission.setPriority(90);
                wcsInboundMission.setIsNest(0);
                wcsInboundMission.setIsPlc(1);
                wcsInboundMission.setIsWms(1);
                StringBuilder sb = new StringBuilder();
                List<String> materialCodeList = nestingMiddleTables.stream().map(NestingMiddleTable::getMaterialCode).distinct().collect(Collectors.toList());
                for (String materialCode : materialCodeList) {
                    if (sb.length() > 0) {
                        sb.append(",");
                    }
                    sb.append(materialCode);
                }
                String materIalCode = sb.toString();
                wcsInboundMission.setMaterialCode(materIalCode);
                //创建入库任务
                lineBodyLog.info("再次创建3f创建入库任务：{}", wcsInboundMission);
                boolean b2 = wcsInboundMissionService.insertInbound(wcsInboundMission);
                if (!b2) {
                    lineBodyLog.error("线体创建入库任务失败，数据库异常");
                    throw new RuntimeException("线体创建入库任务失败，数据库异常");
                }
            }
        }
    }

}
